package com.netty.handler;

import com.netty.CIMWebSocketRequestHandler;
import com.netty.ImWebsocketServer;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;

/**
 * FullHttpRequest
 */

@ChannelHandler.Sharable
public class LoginAuthReqHandler extends ChannelInboundHandlerAdapter {

    private CIMWebSocketRequestHandler cimRequestHandler;

    public LoginAuthReqHandler(CIMWebSocketRequestHandler cimRequestHandler) {
        this.cimRequestHandler = cimRequestHandler;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            // 获取请求头中的身份验证令牌
            boolean authHandler = cimRequestHandler.loginAuthHandler(ctx.channel(), request);
            if(!authHandler){
                ctx.channel().close();
                return;
            }
            ctx.pipeline().remove(this);
            request.setUri(ImWebsocketServer.wsPath);
            // 对事件进行传播，知道完成WebSocket连接。
            ctx.fireChannelRead(msg);
        } else {
            ctx.channel().close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();

        ctx.channel().close();
    }
}
